"""
Markdown导出模块 - 负责提示词导出为Markdown格式
"""

import os
import json
from tkinter import messagebox
import platform
import subprocess

class MarkdownExporter:
    def __init__(self, data_dir: str, output_dir: str):
        self.data_dir = data_dir
        self.output_dir = output_dir

    def export_single_prompt_to_markdown(self, json_path: str) -> tuple:
        """
        导出单个提示词到Markdown文件
        返回：(成功标志, 结果信息) 
        """
        try:
            # 获取源文件最后修改时间
            src_mtime = os.path.getmtime(json_path)
            
            with open(json_path, 'r', encoding='utf-8') as f:
                try:
                    prompt_data = json.load(f)
                except json.JSONDecodeError as je:
                    return (False, f"JSON解析错误: {str(je)}")

            if not prompt_data.get('name'):
                return (False, "缺少name字段")

            # 生成Markdown内容
            markdown_content = f"""### name

{prompt_data.get('name', '')}

### group

{prompt_data.get('group', '')}

### shortcut

{prompt_data.get('shortcut', '')}

### comment

{prompt_data.get('comment', '')}

### content

{prompt_data.get('content', '')}
"""
            # 生成安全文件名
            safe_name = "".join(c for c in prompt_data.get('name', os.path.basename(json_path)) 
                              if c.isalnum() or c in (' ', '-', '_')) or f"unnamed_prompt_{os.path.splitext(os.path.basename(json_path))[0]}"
            
            markdown_path = os.path.join(self.output_dir, f"{safe_name}.md")

            # 判断是否需要导出
            need_export = False
            if not os.path.exists(markdown_path):
                need_export = True
                reason = "新文件"
            else:
                # 比较修改时间
                dst_mtime = os.path.getmtime(markdown_path)
                if src_mtime > dst_mtime:
                    need_export = True
                    reason = "源文件已修改"
                else:
                    # 内容哈希校验
                    with open(markdown_path, 'r', encoding='utf-8') as existing_file:
                        existing_content = existing_file.read()
                    if existing_content != markdown_content:
                        need_export = True
                        reason = "内容有变化"

            if not need_export:
                return (True, "内容未变化")
                
            # 写入文件并同步修改时间
            with open(markdown_path, 'w', encoding='utf-8') as f:
                f.write(markdown_content)
            # 保持与源文件相同的修改时间
            os.utime(markdown_path, (src_mtime, src_mtime))
            
            return (True, f"{reason} - 导出成功")

        except Exception as e:
            return (False, str(e))

    def export_all_prompts_to_markdown(self) -> dict:
        """
        批量导出所有提示词到Markdown
        返回包含统计信息的字典
        """
        stats = {
            'total': 0,
            'success': 0,
            'failed': [],
            'skipped': []
        }

        # 创建输出目录
        if not os.path.exists(self.output_dir):        
            os.makedirs(self.output_dir, exist_ok=True)        

        # 遍历数据目录
        for root, _, files in os.walk(self.data_dir):
            for file in files:
                if not file.endswith('.json'):
                    continue

                stats['total'] += 1
                json_path = os.path.join(root, file)
                
                success, result = self.export_single_prompt_to_markdown(json_path)
                
                if success:
                    if "内容未变化" in result:
                        stats['skipped'].append((file, result))
                    else:
                        stats['success'] += 1
                else:
                    stats['failed'].append((file, result))

        return stats

    def open_export_directory(self):
        """打开导出目录"""
        try:
            if not os.path.exists(self.output_dir):
                os.makedirs(self.output_dir)
                messagebox.showinfo("提示", "导出目录不存在，已创建新目录")

            if platform.system() == 'Windows':
                os.startfile(self.output_dir)
            elif platform.system() == 'Darwin':
                subprocess.run(['open', self.output_dir])
            else:
                subprocess.run(['xdg-open', self.output_dir])
                
        except Exception as e:
            messagebox.showerror("错误", f"打开导出目录失败: {str(e)}")
